package com.zhengxing.jienci.common.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 浪遏飞舟
 * @create 2020-08-24 16:38
 * id生成器
 */
public class IdGenerateUtil {

    private volatile static String ipAddr;

    private final static AtomicInteger index = new AtomicInteger(1000);

    public static String getLocalIpAddr(){
        if (ipAddr != null){
            return ipAddr;
        }
        synchronized (IdGenerateUtil.class){
            if (ipAddr != null){
                return ipAddr;
            }else{
                try {
                    InetAddress ip4 = Inet4Address.getLocalHost();
                    String ipAddress = ip4.getHostAddress();
                    if (ipAddress != null && ipAddress.length() > 4){
                        String ipSuffix = ipAddress.trim().split("\\.")[3];
                        if (ipSuffix.length() == 3){
                            ipAddr = ipSuffix;
                        } else if(ipSuffix.length() == 2){
                            ipAddr = "0" + ipSuffix;
                        } else if (ipSuffix.length() == 1){
                            ipAddr = "00" + ipSuffix;
                        }
                        return ipAddr;
                    }
                    ipAddr =  String.valueOf(new Random().nextInt(99));
                    return ipAddr;
                } catch (UnknownHostException e) {
                    System.out.println("获取ip失败：" + e.getMessage());
                    ipAddr =  String.valueOf(new Random().nextInt(99));
                    return ipAddr;
                }
            }
        }
    }

    /**
     * 生成id(Version 2)
     * @return
     */
    public static String getId(){
        String time = String.valueOf(System.currentTimeMillis());
        if (index.get() > 9999){
            index.set(1000);
        }
        String ip = getLocalIpAddr();
        time = time + ip + index.getAndIncrement();
        return time;
    }
}
